﻿using System;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Web.DynamicData;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NotAClue.ComponentModel.DataAnnotations;
using NotAClue.Web.DynamicData;
using System.Runtime.InteropServices;

namespace DD_Extensions
{
    public partial class PhoneNumber_EditField : System.Web.DynamicData.FieldTemplateUserControl
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            // add tool-tip
            this.SetupTip();

            // set field options
            this.SetFieldOptions();

            // add CSS from meta data
            this.ApplyCss();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Column.MaxLength < 20)
                TextBox1.Columns = Column.MaxLength;

            TextBox1.ToolTip = Column.Description;

            SetUpValidator(RequiredFieldValidator1);
            SetUpValidator(RegularExpressionValidator1);
            SetUpValidator(DynamicValidator1);

            // set validators to use image as error indicator
            this.SetValidatorsToImage();

            // check to see if column is read only in insert mode
            Column.DisableFieldTemplate(Mode, TextBox1);

            TextBox1_MaskedEditExtender.SetupMask(Column);
            if (Mode == DataBoundControlMode.Insert)
                ExtSpan.Visible = true;
        }

        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);
            if (Column.MaxLength > 0)
                TextBox1.MaxLength = Math.Max(FieldValueEditString.Length, Column.MaxLength);

            if (Mode == DataBoundControlMode.Edit)
            {
                if (!String.IsNullOrEmpty(FieldValueEditString) && FieldValueEditString.Contains("|"))
                {
                    var values = FieldValueEditString.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    TextBox1.Text = values[0];
                    TextBox2.Text = values[1];
                    ExtSpan.Visible = true;
                }
                else
                    TextBox1.Text = FieldValueEditString;
            }
        }

        protected override void ExtractValues(IOrderedDictionary dictionary)
        {
            dictionary[Column.Name] = ConvertEditedValue(TextBox1.Text.Trim());
        }

        public override Control DataControl
        {
            get { return TextBox1; }
        }
    }
}
